from app01 import models
from django.shortcuts import render, redirect
from app01.utils.pageination_amd_search import Pagination
from app01.utils.form import AdminModelForm, AdminEditModelForm, AdminResetModelForm


def admin_list(request):
    """管理员列表"""
    # # 检查用户是否登录 已登录，继续向下走，未登录 跳转回登录页面
    # # 用户发来请求 获取COOKIE随机字符串 有即登录 没有即未登录
    # info_dict = request.session['info']
    # print('session', info_dict)


    # 搜索模块
    data_dict = {}
    search_data = request.GET.get("q", "")
    if search_data:
        data_dict['username__contains'] = search_data
    # 数据源
    queryset = models.Admin.objects.filter(**data_dict)
    # 传递数据源
    page_object = Pagination(request, queryset=queryset, pege_size=5)
    context = {
        'search_data': search_data,
        'page_queryset': page_object.page_queryset,
        'page_string': page_object.html(),
    }
    return render(request,
                  'admin_list.html',
                  context)


def admin_add(request):
    """添加管理员"""

    title = "新建管理员"
    if request.method == "GET":
        form = AdminModelForm()
        return render(request,
                      'change.html',
                      {'title': title, 'form': form})
    # 将网页填充的数据进行接收并保存 然后网页重定向到管理员列表页面
    form = AdminModelForm(request.POST)
    if form.is_valid():
        # print(form.cleaned_data)
        # {'username': 'roor', 'password': '123', 'confirm_password': '1234'}
        instance = form
        instance.save()
        return redirect('/admin/list/')
    return render(request,
                  'change.html',
                  {'form': form, 'title': title})


def admin_edit(request, nid):
    """添加管理员"""

    msg = "数据不存在！"
    row_object = models.Admin.objects.filter(id=nid).first()
    if not row_object:
        # 可以自定义一个错误页面
        return render(request,
                      'error.html',
                      {'msg': msg})

    title = "编辑管理员信息"
    if request.method == "GET":
        # 原始数据 默认值
        form = AdminEditModelForm(instance=row_object)
        return render(request,
                      'change.html',
                      {'form': form, 'title': title})
    form = AdminEditModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        instance = form
        instance.save()
        return redirect('/admin/list')
    return render(request, 'change.html', {'form': form, 'title': title})


def admin_del(request, nid):
    models.Admin.objects.filter(id=nid).delete()
    return redirect("/admin/list/")


def admin_reset(request, nid):
    """重置密码功能"""
    row_object = models.Admin.objects.filter(id=nid).first()
    if not row_object:
        # 可以自定义一个错误页面
        return redirect('/admin/list/')
    #                          不设置instance=row_object就不会传
    title = f"重置{row_object.username}密码"

    if request.method == "GET":
        form = AdminResetModelForm()
        return render(request,
                      'change.html',
                      {'title': title, 'form': form})
    form = AdminResetModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        instance = form
        instance.save()
        return redirect('/admin/list/')
    return render(request,
                  'change.html',
                  {'title': title, 'form': form})
